package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.github.pagehelper.PageInfo;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.InstructionDicRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.InstructionRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.Instruction;
import com.ktwlsoft.archivemanage.domain.dao.entity.InstructionDic;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.instruction.InstrctionSaveRequest;
import com.ktwlsoft.archivemanage.payload.instruction.InstrctionUpdateRequest;
import com.ktwlsoft.archivemanage.payload.instruction.InstructionPageRequest;
import com.ktwlsoft.archivemanage.payload.instruction.InstructionPageRespose;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @author JokerMo
 * @version 1.0
 * @date 2019/12/12 14:18
 */
@Component
public class InstructionService {

    /**
     * 指南
     */
    private final InstructionRepositoryService instructionRepositoryService;
    private final InstructionDicRepositoryService instructionDicRepositoryService;


    public InstructionService(InstructionRepositoryService instructionRepositoryService, InstructionDicRepositoryService instructionDicRepositoryService) {
        this.instructionRepositoryService = instructionRepositoryService;
        this.instructionDicRepositoryService = instructionDicRepositoryService;
    }

    /**
     * 指南分页列表
     *
     * @return Result<Instruction>
     */
    public Result<Instruction> findPage(InstructionPageRequest request) {
        PageInfo<Instruction> pageInfo = instructionRepositoryService.findPage(request);
        return Result.ok(pageInfo);
    }

    /**
     * 指南详情
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> getById(Long id) throws UnsupportedEncodingException {
        if (id == null || id <= 0) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        Instruction instruction = instructionRepositoryService.getById(id);
        String content = new String(instruction.getContent(), "utf-8");
        InstructionPageRespose respose = new InstructionPageRespose();
        respose.setBelong(instruction.getBelong());
        respose.setBelongId(instruction.getBelongId());
        respose.setContent(content);
        respose.setId(instruction.getId());
        respose.setTag(instruction.getTag());
        respose.setTitle(instruction.getTitle());
        respose.setOperatedAt(instruction.getOperatedAt());
        if (respose == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        return Result.ok(respose);
    }

    /**
     * 指南新增
     *
     * @param request request
     * @return Result<?>
     */
    public Result<?> save(InstrctionSaveRequest request) throws UnsupportedEncodingException {
        Instruction instruction = new Instruction();
        BeanUtils.copyProperties(request, instruction);
        byte[] content = request.getContent().getBytes("utf-8");
        instruction.setContent(content);
        Account account = UserPrincipal.getCurrentUser();
        instruction.setCreator(account.getRealName());
        instruction.setCreatorId(account.getId());
        instruction.setOperater(account.getRealName());
        instruction.setOperaterId(account.getId());
        InstructionDic instructionDic = instructionDicRepositoryService.getById(request.getBelongId());
        instruction.setBelong(instructionDic.getName());
        instruction.setState(request.getUp() ? Instruction.State.UP : Instruction.State.WAIT_UP);
        try {
            instructionRepositoryService.insert(instruction);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(instruction.getId());
    }

    /**
     * 指南修改
     *
     * @param request request
     * @return Result<?>
     */
    public Result<?> edit(InstrctionUpdateRequest request) throws UnsupportedEncodingException {
        Instruction instruction = instructionRepositoryService.getById(request.getId());
        if (instruction == null) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        instruction.setTitle(request.getTitle());
        instruction.setBelongId(request.getBelongId());
        instruction.setContent(request.getContent().getBytes("utf-8"));
        instruction.setBusinessFrom(request.getBusinessFrom());
        instruction.setTag(request.getTag());
        instruction.setState(request.getUp() ? Instruction.State.UP : instruction.getState());
        InstructionDic instructionDic = instructionDicRepositoryService.getById(request.getBelongId());
        instruction.setBelong(instructionDic.getName());
        Account account = UserPrincipal.getCurrentUser();
        instruction.setOperater(account.getRealName());
        instruction.setOperaterId(account.getId());
        try {
            instructionRepositoryService.update(instruction);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.UPDATE_ERROR);
        }
        return Result.ok(instruction.getId());
    }

    /**
     * 指南删除
     *
     * @param id id
     * @return Result<?>
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteById(Long id) {
        if (id == null || id <= 0) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("id不能为空");
        }
        Instruction instruction = instructionRepositoryService.getById(id);
        if (instruction == null) {
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        try {
            instructionRepositoryService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.DELETE_ERROR);
        }
        return Result.ok(instruction.getId());
    }

    /**
     * 指南上下架
     *
     * @param id
     * @param state
     * @return
     */
    public int upOrDownById(Long id, Instruction.State state) {
        Account account = UserPrincipal.getCurrentUser();
        return instructionRepositoryService.getInstructionMapper().upOrDownById(id, state, new Date(), account.getRealName(), account.getId());
    }

    /**
     * 处理value on 2019/11/5 9:46
     *
     * @param instruction instruction
     * @return 字段存在true, 不存在false
     */
    private boolean handelValue(Instruction instruction) {
        if (instruction.getTitle() == null || instruction.getTitle() == null || "".equals(instruction.getTitle())) {
            return false;
        }
        List<Instruction> instructions = instructionRepositoryService.getByTitle(instruction);
        if (instructions != null && instructions.size() > 0) {
            for (Instruction item : instructions) {
                if (!item.getId().equals(instruction.getId())) {
                    return true;
                }
            }
        }
        return false;
    }
}
